import 'package:schedule_self_client/api/user_center/user_info_dto.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserInfo {
  static const String tokenKey = 'user_token';
  static const String usernameKey = 'username';
  static const String avatarUrlKey = 'user_avatar_url';
  static const String nickNameKey = 'user_nick_name';
  static const String emailKey = 'user_email';

  String? token;
  String? username;
  String? avatarUrl;
  String? nickName;
  String? email;

  UserInfo._();

  static Future<void> clearCache() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove(tokenKey);
    prefs.remove(usernameKey);
    prefs.remove(avatarUrlKey);
    prefs.remove(nickNameKey);
    prefs.remove(emailKey);
  }

  static Future<void> cache(String? username, String? nickName,
      String? avatarUrl, String? email, String? token) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(tokenKey, token ?? '');
    prefs.setString(usernameKey, username ?? '');
    prefs.setString(avatarUrlKey, avatarUrl ?? '');
    prefs.setString(nickNameKey, nickName ?? '');
    prefs.setString(emailKey, email ?? '');
  }

  static Future<UserInfo> initWithCache() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    UserInfo userInfo = UserInfo._();
    userInfo.token = prefs.getString(tokenKey);
    userInfo.username = prefs.getString(usernameKey);
    userInfo.avatarUrl = prefs.getString(avatarUrlKey);
    userInfo.nickName = prefs.getString(nickNameKey);
    userInfo.email = prefs.getString(emailKey);
    return userInfo;
  }

  static UserInfo initBy(UserInfoDto? userInfoDto, String? token) {
    UserInfo userInfo = UserInfo._();
    userInfo.token = token;
    if (userInfoDto != null) {
      userInfo.username = userInfoDto.username;
      userInfo.nickName = userInfoDto.nickName;
      userInfo.avatarUrl = userInfoDto.avatarUrl;
      userInfo.email = userInfoDto.email;
    }
    return userInfo;
  }
}
